const http = require('http');
const fs = require('fs');
const path = require('path');
const url = require('url');

// 配置参数
const PORT = 3000;
const HOST = 'localhost';
const ROOT_DIR = path.join(__dirname, 'dist'); // 托管目录

// 创建 HTTP 服务器
const server = http.createServer((req, res) => {
    // 解析请求路径
    const parsedUrl = url.parse(req.url);
    let pathname = path.join(ROOT_DIR, parsedUrl.pathname);

    // 安全校验：防止路径穿越攻击
    if (!pathname.startsWith(path.resolve(ROOT_DIR))) {
        res.statusCode = 403;
        res.end('Forbidden');
        return;
    }

    fs.stat(pathname, (err, stats) => {
        // 处理文件不存在
        if (err) {
            res.statusCode = 404;
            res.end('File not found');
            return;
        }

        // 如果是目录，自动寻找 index.html
        if (stats.isDirectory()) {
            pathname = path.join(pathname, 'index.html');
        }

        // 读取文件并返回
        fs.readFile(pathname, (err, data) => {
            if (err) {
                res.statusCode = 404;
                res.end('File not found');
                return;
            }

            // 根据扩展名设置 Content-Type
            const ext = path.parse(pathname).ext;
            const mimeTypes = {
                '.html': 'text/html',
                '.js': 'text/javascript',
                '.css': 'text/css',
                '.json': 'application/json',
                '.png': 'image/png',
                '.jpg': 'image/jpeg',
                '.gif': 'image/gif',
                '.svg': 'image/svg+xml',
                '.woff': 'font/woff',
                '.woff2': 'font/woff2'
            };

            res.setHeader('Content-Type', mimeTypes[ext] || 'application/octet-stream');
            res.end(data);
        });
    });
});

// 启动服务器
server.listen(PORT, HOST, () => {
    console.log(`Server running at http://${HOST}:${PORT}/`);
    console.log(`Serving files from: ${ROOT_DIR}`);
});